package com.h.handler;

import com.h.annotation.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @author ：Hukaiwen
 * @description：
 * @date ：2022/2/22 15:32
 */
@Handler("myhandler3")
public class MyHandler3 extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg)  throws Exception
            {
                //处理收到的数据，并反馈消息到到客户端
                ByteBuf in = (ByteBuf) msg;
                System.out.println("收到客户端发过来的消息: "+ in.toString(CharsetUtil.UTF_8));

                //写入并发送信息到远端（客户端）
                ctx.writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已经收到你发送的消息", Charset.forName("GBK")));
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
            {
                //出现异常的时候执行的动作（打印并关闭通道）
                cause.printStackTrace();
                ctx.close();
            }
        });
    }
}
